<?php

namespace App\Services\MakeBoxProductOrder;

use App\Models\Order;
use App\Models\Address;
use App\Models\BlindBox;
use Carbon\Carbon;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class MakeBoxProductOrderRequest extends FormRequest
{
	protected ?Address $address = null;

	public function rules(): array
	{

		$addressId =  (int)request('address_id');
		if ($addressId) {
			$this->address = Address::find($addressId);
		}

		$blindBoxId =  (int)request('blind_box_id');
		if ($blindBoxId) {
			$this->blindBox = BlindBox::find($blindBoxId);
		}

		return [
			'address_id' => ['required', $this->address()],
			'blind_box_id' => ['required', $this->box()],
			'user_coupon_id' => ['required', $this->coupon()],
		];
	}

	public function address()
	{
		return function ($attribute, $value, $fail) {
			if (!$this->address) {
				return $fail('地址不存在');
			} elseif (!Order::isAddressSupported($this->address)) {
				return $fail('地址不在配送范围');
			}
			return true;
		};
	}

	public function coupon()
	{
		return function ($attribute, $value, $fail) {

			if (!$coupon = $this->user()->coupons->where("id",$value)->first()) {
				return $fail('优惠卷不存在');
			}elseif($coupon->is_used == 1){

				return $fail('优惠卷已使用');
			}elseif(Carbon::now()->gt($coupon->destory_at)){
				return $fail('优惠卷已过期');
			}
			return true;
		};
	}

	public function box()
	{
		return function ($attribute, $value, $fail) {
			if (!$box = BlindBox::find($value)) {
				return $fail('此盲盒不存在');
			}else{
				if(!$products = $box->blindBoxProducts->toArray()){
					return $fail('此盲盒下没有商品');
				}
			} 
			return true;
		};
	}

	public function getAddress(): Address
	{
		return $this->address;
	}

	public function getBlindBox()
	{
		return $this->blindBox;
	}

	
}
